//
//  KPChooseCityViewController.swift
//  KPBaseProject
//
//  Created by Kipp Dev on 2018/4/4.
//  Copyright © 2018年 Kipp. All rights reserved.
//

// swiftlint:disable force_try

import UIKit
import HandyJSON
import RxSwift

class KPChooseCityViewController: KPBaseTableViewController {

    fileprivate var originDataSource = [(String, [RegionEntitysModel])]()///元组类型的数据
    fileprivate var openCitys = [OpenCityModel]()
    fileprivate var filterDataSource = [(String, [RegionEntitysModel])]()///筛选数组
    fileprivate var searchTF: UITextField!

    var selectCityClosure: ((_ city: String) -> Void)?

    override func viewDidLoad() {
        super.viewDidLoad()
        prepareView()
        gcdKit.globalQueue.async {
            self.prepareJSON()
        }
        getData()

    }

    // MARK: - 创建视图
    fileprivate func prepareView() {
        tableView.sectionIndexColor = mainColor

        searchTF = UITextField().then {
            $0.placeholder = "请输入城市"
            $0.leftPaddingWidth = 24
            $0.font = 16.font
            $0.textColor = mainTextColor
            $0.borderStyle = .none
            $0.layer.borderColor = UIColor.lineColor.cgColor
            $0.backgroundColor = mainBackgroundColor
            $0.tintColor = mainColor
            $0.borderWidth = 0.5
            $0.bounds = CGRect.init(x: 0, y: 0, width: 260.adaption, height: 28)
            $0.cornerRadius = 14
            navigationItem.titleView = $0
            $0.rx.text
                .throttle(0.3, scheduler: MainScheduler.asyncInstance)
                .distinctUntilChanged()
                .asObservable()
                .observeOn(MainScheduler.instance)
                .subscribe(onNext: { [weak self] (text) in
                    KPLog(text)
                    self?.filterDataSource.removeAll()

                    if !text.or("").isEmpty {
                        self?.originDataSource.forEach({ (item) in
                            self?.filterDataSource.append((item.0, item.1.filter { $0.pinyin.contains(text!) || $0.name.contains(text!) }))
                        })
                        self?.filterDataSource = (self?.filterDataSource.filter { !$0.1.isEmpty })!
                    }
                    self?.tableView.reloadData()
                })
                .disposed(by: bag)
        }

    }

    // MARK: - 获取网络数据
    @objc
    fileprivate func getData() {
        Api.getJSONRequest(.获取开通城市列表, parameters: nil)
            .mapArray(OpenCityModel.self)
            .subscribe(onNext: { [weak self] (model) in
                self?.openCitys = model.data.or([]).compactMap { $0 }///排除空值，防止意外崩溃
                self?.tableView.reloadData()
            })
            .disposed(by: bag)
    }

    fileprivate func prepareJSON() {
        let path = Bundle.main.path(forResource: "citys", ofType: "json")
        let datas = try! Data(contentsOf: URL.init(fileURLWithPath: path!), options: .mappedIfSafe)
        let jsonArray = try! JSONSerialization.jsonObject(with: datas, options: JSONSerialization.ReadingOptions.allowFragments) as! [Any] /// 数据当做任意类型的数组来用

        //json 转 model
        let models = JSONDeserializer<CityModel>.deserializeModelArrayFrom(array: jsonArray)

        /// compactMap 过滤掉空值，在 compactMap 用flatMap 打平子数组,现在数组类型为[[1,2,3],[4,5]]，再用 flatMap 打平 ，现在数据类型为 [1,2,3,4,5],再用 groupByKey 方法进行分组处理，将 模型的 first 属性作为 字典的Key
        let modelArr = models?.compactMap { $0.flatMap { $0.citylist } }.flatMap { $0 }.groupByKey { $0.first }
        modelArr?.forEach { originDataSource.append(($0.key, $0.value)) }//遍历数组将其加入到数据源中，

        originDataSource = originDataSource.sorted { (data1, data2) -> Bool in
            return data1.0 < data2.0
        }///排序

        gcdKit.mainQueue.async {
            self.tableView.reloadData()
        }

    }

    struct CityModel: HandyJSON {
        var code: String!
        var name: String!
        var citylist = [RegionEntitysModel]()
    }

    struct RegionEntitysModel: HandyJSON {
        var pinyin: String!
        var first: String!
        var code: String!
        var name: String!
        var arealist = [CityModel]()

    }

    struct OpenCityModel: HandyJSON {
        var id: String!
        var cityName: String!
        var provinceName: String!
        var createTime: String!
        var state: String!
    }
}

extension KPChooseCityViewController {
    override func numberOfSections(in tableView: UITableView) -> Int {
        guard filterDataSource.isEmpty else {
            return filterDataSource.count
        }
        return originDataSource.count + 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        guard filterDataSource.isEmpty else {
            return filterDataSource[section].1.count
        }

        guard section > 0 else {
            return openCitys.count
        }
        return originDataSource[section - 1].1.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") ?? UITableViewCell.init(style: .default, reuseIdentifier: "cell").then {
            $0.textLabel?.font = 16.font
            $0.textLabel?.textColor = mainTextColor
        }

        guard filterDataSource.isEmpty else {
            cell.textLabel?.text = filterDataSource[indexPath.section].1[indexPath.row].name
            return cell
        }

        guard indexPath.section > 0 else {
            cell.textLabel?.text = openCitys[indexPath.row].cityName
            return cell
        }

        cell.textLabel?.text = originDataSource[indexPath.section - 1].1[indexPath.row].name
        return cell
    }

    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

        guard filterDataSource.isEmpty else {
            return filterDataSource[section].0
        }

        guard section > 0 else {
            return "已开通城市"
        }
        return originDataSource[section - 1].0
    }

    override func sectionIndexTitles(for tableView: UITableView) -> [String]? {

        guard filterDataSource.isEmpty else {
            return filterDataSource.compactMap { $0.0 }
        }

        var titles = originDataSource.compactMap { $0.0 }
        titles.insert("开通", at: 0)
        return titles
    }

    override func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
        return index
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        guard selectCityClosure != nil else {
            assert(true, "必须传递闭包！")
            return
        }
        guard filterDataSource.isEmpty else {
            if selectCityClosure != nil {
                selectCityClosure!(filterDataSource[indexPath.section].1[indexPath.row].name)
                navigationController?.popViewController()
            }
            return
        }

        guard indexPath.section > 0 else {
            selectCityClosure!(openCitys[indexPath.row].cityName)
            navigationController?.popViewController()
            return
        }

        selectCityClosure!(originDataSource[indexPath.section - 1].1[indexPath.row].name)
        navigationController?.popViewController()
    }

}
